package cn.bus.controller;

import cn.bus.domain.Car;
import cn.bus.service.CarService;
import cn.bus.vo.CarVo;
import cn.sys.utils.AppFileUtils;
import cn.sys.utils.DataGridView;
import cn.sys.utils.ResultObj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @author Mxb
 * @version 1.0
 * @date 2019/11/2 21:18
 * 控制器
 */
@RestController
@RequestMapping("car")

public class CarController {
    @Autowired
    private CarService carService;

    @RequestMapping("loadAllCar")
    public DataGridView loadAllCar(CarVo carVo) {
        return this.carService.queryAllCar(carVo);
    }

    //添加车辆
    @RequestMapping("addCar")
    public ResultObj addCar(CarVo carVo) {
        try {
            //自动创建时间
            carVo.setCreatetime(new Date());
            //如果不是默认图片就去掉图片的_temp后缀
            if (!carVo.getCarimg().equals("images/uu.jpg")) {
                String filePath = AppFileUtils.updateFileName(carVo.getCarimg(), "_temp");
                carVo.setCarimg(filePath);
            }
            this.carService.addCar(carVo);
            return ResultObj.ADD_SUCCESS;
        } catch (Exception d) {
            d.printStackTrace();
            return ResultObj.ADD_ERROR;
        }
    }

    //修改车辆
    @RequestMapping("updateCar")
    public ResultObj updateCar(CarVo carVo) {
        try {
            String carimg = carVo.getCarimg();
            //不是以temp 结尾的图片
            if (carimg.endsWith("_temp")) {
                String filePath = AppFileUtils.updateFileName(carVo.getCarimg(), "_temp");
                carVo.setCarimg(filePath);

                //不是默认文件
                Car car = this.carService.queryCarByCarNumber(carVo.getCarnumber());
                AppFileUtils.removeFileByPath(car.getCarimg());
            }
            this.carService.updateCar(carVo);
            return ResultObj.UPDATE_SUCCESS;
        } catch (Exception d) {
            d.printStackTrace();
            return ResultObj.UPDATE_ERROR;
        }
    }

    //根据id删除车辆
    @RequestMapping("deleteCarById")
    public ResultObj deleteCar(CarVo carVo) {
        try {
            this.carService.deleteCarById(carVo.getCarnumber());
            return ResultObj.DELETE_SUCCESS;
        } catch (Exception d) {
            d.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }

    //批量删除车辆
    @RequestMapping("deleteBatchCar")
    public ResultObj deleteBatchCar(CarVo CarVo) {
        try {
            this.carService.deleteBatchCar(CarVo.getIds());
            return ResultObj.DELETE_SUCCESS;
        } catch (Exception d) {
            d.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }


}
